package cn.kk.xss;


import lombok.extern.slf4j.Slf4j;
import org.owasp.validator.html.*;

import java.util.Objects;


/**
 * XSS漏洞防护策略具体实现类 目前采用的是OWASP下的AntiSamy提供的防护策略
 * @Author: kk
 * @Date: 2023/3/5  14:56
 * @Version 1.0
 */
@Slf4j
public class XssEncode {

    private static Policy policy;

    // 加载默认预防策略文件(需要从依赖包中拷贝到resource路径下，可自行选择策略和修改)
    static {
        String path = Objects.requireNonNull(XssEncode.class.getClassLoader().getResource("antisamy-anythinggoes.xml")).getFile();
        try {
            policy = Policy.getInstance(path);
        } catch (PolicyException e) {
            log.error("[XSS预防策略加载异常]:", e);
        }
    }

    public static String xssEncode(String str) {
        // XSS漏洞处理具体实现
        AntiSamy antiSamy = new AntiSamy();
        try {
            final CleanResults cr = antiSamy.scan(str, policy);
            return cr.getCleanHTML();
        } catch (ScanException | PolicyException e) {
            log.error("[XSS预防策略解析异常]:", e);
        }
        return str;
    }

    public static void main(String[] args) {
        System.out.println(xssEncode("张三><script>alert('XSS');</script>"));
    }

}
